﻿using System;
using System.Collections.Generic;
using System.Linq;
using Autodesk.Revit.DB;

namespace YJKRevitKernel.CurveUtility.ColinearCurveGroup
{
	internal class ColinearCurveConnector
	{
		internal ColinearCurveConnector(Curve inputBaseLine, List<Curve> inputGroupingCurve)
		{
			this.m_useBaseLine = inputBaseLine;
			this.m_lstGroupingCurve = inputGroupingCurve;
		}

		internal List<Curve> Connect()
		{
			this.PrepareData();
			List<ConnectCurveInfo> list = new List<ConnectCurveInfo>();
			List<Curve> list2 = new List<Curve>();
			int num = -1;
			foreach (ConnectCurveInfo connectCurveInfo in this.m_lstSortCurve)
			{
				num++;
				list.Add(connectCurveInfo);
				if (num + 1 < this.m_lstSortCurve.Count && this.m_lstSortCurve[num].UsePoint.IsAlmostEqualTo(this.m_lstSortCurve[num + 1].UsePoint) && this.m_lstSortCurve[num].UseCurve != this.m_lstSortCurve[num + 1].UseCurve)
				{
					this.CheckConnecState(connectCurveInfo);
				}
				else if (this.CheckConnecState(connectCurveInfo))
				{
					if (list.Count.Equals(2))
					{
						list2.Add(connectCurveInfo.UseCurve);
					}
					else
					{
						list2.Add(Line.CreateBound(list.First<ConnectCurveInfo>().UsePoint, list.Last<ConnectCurveInfo>().UsePoint));
					}
					list.Clear();
					this.m_dicConnectCurve.Clear();
				}
			}
			return list2;
		}

		private void PrepareData()
		{
			foreach (Curve curve in this.m_lstGroupingCurve)
			{
				this.m_lstSortCurve.Add(new ConnectCurveInfo(this.m_useBaseLine.Project(curve.GetEndPoint(0)).Parameter, curve, curve.GetEndPoint(0)));
				this.m_lstSortCurve.Add(new ConnectCurveInfo(this.m_useBaseLine.Project(curve.GetEndPoint(1)).Parameter, curve, curve.GetEndPoint(1)));
			}
			this.m_lstSortCurve = (from k in this.m_lstSortCurve
			orderby k.Parameter
			select k).ToList<ConnectCurveInfo>();
		}

		private bool CheckConnecState(ConnectCurveInfo inputInfo)
		{
			if (!this.m_dicConnectCurve.ContainsKey(inputInfo.UseCurve))
			{
				this.m_dicConnectCurve.Add(inputInfo.UseCurve, false);
			}
			else
			{
				this.m_dicConnectCurve[inputInfo.UseCurve] = true;
			}
			using (Dictionary<Curve, bool>.ValueCollection.Enumerator enumerator = this.m_dicConnectCurve.Values.GetEnumerator())
			{
				while (enumerator.MoveNext())
				{
					if (!enumerator.Current)
					{
						return false;
					}
				}
			}
			return true;
		}

		private Curve m_useBaseLine;

		private List<Curve> m_lstGroupingCurve;

		private List<ConnectCurveInfo> m_lstSortCurve = new List<ConnectCurveInfo>();

		private Dictionary<Curve, bool> m_dicConnectCurve = new Dictionary<Curve, bool>();
	}
}
